{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bf37a837-7a6a-447b-8779-38f26c585887",
   "metadata": {},
   "source": [
    "# Build a semantic search engine\n",
    "\n",
    "This tutorial will familiarize you with LangChain's [document loader](/docs/concepts/document_loaders), [embedding](/docs/concepts/embedding_models), and [vector store](/docs/concepts/vectorstores) abstractions. These abstractions are designed to support retrieval of data--  from (vector) databases and other sources--  for integration with LLM workflows. They are important for applications that fetch data to be reasoned over as part of model inference, as in the case of retrieval-augmented generation, or [RAG](/docs/concepts/rag) (see our RAG tutorial [here](/docs/tutorials/rag)).\n",
    "\n",
    "Here we will build a search engine over a PDF document. This will allow us to retrieve passages in the PDF that are similar to an input query.\n",
    "\n",
    "## Concepts\n",
    "\n",
    "This guide focuses on retrieval of text data. We will cover the following concepts:\n",
    "\n",
    "- Documents and document loaders;\n",
    "- Text splitters;\n",
    "- Embeddings;\n",
    "- Vector stores and retrievers.\n",
    "\n",
    "## Setup\n",
    "\n",
    "### Jupyter Notebook\n",
    "\n",
    "This and other tutorials are perhaps most conveniently run in a Jupyter notebook. See [here](https://jupyter.org/install) for instructions on how to install.\n",
    "\n",
    "### Installation\n",
    "\n",
    "This guide requires `@langchain/community` and `pdf-parse`:\n",
    "\n",
    "```{=mdx}\n",
    "import Npm2Yarn from '@theme/Npm2Yarn';\n",
    "import TabItem from '@theme/TabItem';\n",
    "import CodeBlock from \"@theme/CodeBlock\";\n",
    "\n",
    "<Npm2Yarn>\n",
    "  @langchain/community pdf-parse\n",
    "</Npm2Yarn>\n",
    "```\n",
    "\n",
    "For more details, see our [Installation guide](/docs/how_to/installation/).\n",
    "\n",
    "### LangSmith\n",
    "\n",
    "Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls.\n",
    "As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent.\n",
    "The best way to do this is with [LangSmith](https://smith.langchain.com).\n",
    "\n",
    "After you sign up at the link above, make sure to set your environment variables to start logging traces:\n",
    "\n",
    "```shell\n",
    "export LANGSMITH_TRACING=\"true\"\n",
    "export LANGSMITH_API_KEY=\"...\"\n",
    "\n",
    "# Reduce tracing latency if you are not in a serverless environment\n",
    "# export LANGCHAIN_CALLBACKS_BACKGROUND=true\n",
    "```\n",
    "\n",
    "\n",
    "## Documents and Document Loaders\n",
    "\n",
    "LangChain implements a [Document](https://api.js.langchain.com/classes/_langchain_core.documents.Document.html) abstraction, which is intended to represent a unit of text and associated metadata. It has three attributes:\n",
    "\n",
    "- `pageContent`: a string representing the content;\n",
    "- `metadata`: records of arbitrary metadata;\n",
    "- `id`: (optional) a string identifier for the document.\n",
    "\n",
    "The `metadata` attribute can capture information about the source of the document, its relationship to other documents, and other information. Note that an individual `Document` object often represents a chunk of a larger document.\n",
    "\n",
    "We can generate sample documents when desired:\n",
    "```javascript\n",
    "import { Document } from \"@langchain/core/documents\";\n",
    "\n",
    "const documents = [\n",
    "    new Document({\n",
    "        pageContent: \"Dogs are great companions, known for their loyalty and friendliness.\",\n",
    "        metadata: {\"source\": \"mammal-pets-doc\"},\n",
    "    }),\n",
    "    new Document({\n",
    "        pageContent: \"Cats are independent pets that often enjoy their own space.\",\n",
    "        metadata: {\"source\": \"mammal-pets-doc\"},\n",
    "    }),\n",
    "]\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8593578-5699-4b19-96c4-7c990d37a2ec",
   "metadata": {},
   "source": [
    "However, the LangChain ecosystem implements [document loaders](/docs/concepts/document_loaders) that [integrate with hundreds of common sources](/docs/integrations/document_loaders/). This makes it easy to incorporate data from these sources into your AI application.\n",
    "\n",
    "### Loading documents\n",
    "\n",
    "Let's load a PDF into a sequence of `Document` objects. There is a sample PDF in the LangChain repo [here](https://github.com/langchain-ai/langchainjs/blob/main/docs/core_docs/data/nke-10k-2023.pdf) -- a 10-k filing for Nike from 2023. LangChain implements a [PDFLoader](/docs/integrations/document_loaders/file_loaders/pdf/) that we can use to parse the PDF:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "67c39f96-b1f0-4610-979f-fe2d4d164e08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33m107\u001b[39m\n"
     ]
    }
   ],
   "source": [
    "import { PDFLoader } from \"@langchain/community/document_loaders/fs/pdf\";\n",
    "\n",
    "const loader = new PDFLoader(\"../../data/nke-10k-2023.pdf\");\n",
    "\n",
    "const docs = await loader.load();\n",
    "console.log(docs.length)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b90f4800-bb82-416b-beba-f42ae88a5c66",
   "metadata": {},
   "source": [
    "```{=mdx}\n",
    ":::tip\n",
    "\n",
    "See [this guide](/docs/how_to/document_loader_pdf/) for more detail on PDF document loaders.\n",
    "\n",
    ":::\n",
    "```\n",
    "\n",
    "`PDFLoader` loads one `Document` object per PDF page. For each, we can easily access:\n",
    "\n",
    "- The string content of the page;\n",
    "- Metadata containing the file name and page number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "321001d0-ffba-4c86-af92-33871215525f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Table of Contents\n",
      "UNITED STATES\n",
      "SECURITIES AND EXCHANGE COMMISSION\n",
      "Washington, D.C. 20549\n",
      "FORM 10-K\n",
      "(Mark One)\n",
      "☑ ANNUAL REPORT PURSUANT TO SECTION 13 OR 15(D) OF THE SECURITIES EXCHANGE ACT OF 1934\n",
      "FO\n"
     ]
    }
   ],
   "source": [
    "docs[0].pageContent.slice(0, 200)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d3ad3445-6090-46c8-b67c-99a42c5485ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  source: \u001b[32m'../../data/nke-10k-2023.pdf'\u001b[39m,\n",
      "  pdf: {\n",
      "    version: \u001b[32m'1.10.100'\u001b[39m,\n",
      "    info: {\n",
      "      PDFFormatVersion: \u001b[32m'1.4'\u001b[39m,\n",
      "      IsAcroFormPresent: \u001b[33mfalse\u001b[39m,\n",
      "      IsXFAPresent: \u001b[33mfalse\u001b[39m,\n",
      "      Title: \u001b[32m'0000320187-23-000039'\u001b[39m,\n",
      "      Author: \u001b[32m'EDGAR Online, a division of Donnelley Financial Solutions'\u001b[39m,\n",
      "      Subject: \u001b[32m'Form 10-K filed on 2023-07-20 for the period ending 2023-05-31'\u001b[39m,\n",
      "      Keywords: \u001b[32m'0000320187-23-000039; ; 10-K'\u001b[39m,\n",
      "      Creator: \u001b[32m'EDGAR Filing HTML Converter'\u001b[39m,\n",
      "      Producer: \u001b[32m'EDGRpdf Service w/ EO.Pdf 22.0.40.0'\u001b[39m,\n",
      "      CreationDate: \u001b[32m\"D:20230720162200-04'00'\"\u001b[39m,\n",
      "      ModDate: \u001b[32m\"D:20230720162208-04'00'\"\u001b[39m\n",
      "    },\n",
      "    metadata: \u001b[1mnull\u001b[22m,\n",
      "    totalPages: \u001b[33m107\u001b[39m\n",
      "  },\n",
      "  loc: { pageNumber: \u001b[33m1\u001b[39m }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "docs[0].metadata"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ca6980f-4870-490a-9fe6-8caeead3c1d1",
   "metadata": {},
   "source": [
    "### Splitting\n",
    "\n",
    "For both information retrieval and downstream question-answering purposes, a page may be too coarse a representation. Our goal in the end will be to retrieve `Document` objects that answer an input query, and further splitting our PDF will help ensure that the meanings of relevant portions of the document are not \"washed out\" by surrounding text.\n",
    "\n",
    "We can use [text splitters](/docs/concepts/text_splitters) for this purpose. Here we will use a simple text splitter that partitions based on characters. We will split our documents into chunks of 1000 characters\n",
    "with 200 characters of overlap between chunks. The overlap helps\n",
    "mitigate the possibility of separating a statement from important\n",
    "context related to it. We use the\n",
    "[RecursiveCharacterTextSplitter](/docs/how_to/recursive_text_splitter),\n",
    "which will recursively split the document using common separators like\n",
    "new lines until each chunk is the appropriate size. This is the\n",
    "recommended text splitter for generic text use cases.\n",
    "\n",
    "We set `add_start_index=True` so that the character index where each\n",
    "split Document starts within the initial Document is preserved as\n",
    "metadata attribute “start_index”.\n",
    "\n",
    "See [this guide](/docs/how_to/document_loader_pdf/) for more detail about working with PDFs. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5a287c2b-9623-4ef6-8720-fb31189730a0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33m513\u001b[39m\n"
     ]
    }
   ],
   "source": [
    "import { RecursiveCharacterTextSplitter } from \"@langchain/textsplitters\";\n",
    "\n",
    "const textSplitter = new RecursiveCharacterTextSplitter({\n",
    "  chunkSize: 1000,\n",
    "  chunkOverlap: 200,\n",
    "});\n",
    "\n",
    "const allSplits = await textSplitter.splitDocuments(docs)\n",
    "\n",
    "allSplits.length"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c066d46-9187-4d5a-98d3-974c37610276",
   "metadata": {},
   "source": [
    "## Embeddings\n",
    "\n",
    "Vector search is a common way to store and search over unstructured data (such as unstructured text). The idea is to store numeric vectors that are associated with the text. Given a query, we can [embed](/docs/concepts/embedding_models) it as a vector of the same dimension and use vector similarity metrics (such as cosine similarity) to identify related text.\n",
    "\n",
    "LangChain supports embeddings from [dozens of providers](/docs/integrations/text_embedding/). These models specify how text should be converted into a numeric vector. Let's select a model.\n",
    "\n",
    "```{=mdx}\n",
    "import EmbeddingTabs from \"@theme/EmbeddingTabs\";\n",
    "\n",
    "<EmbeddingTabs customVarName=\"embeddings\" />\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "90b06c22-44bb-4d10-9bc4-f6a3a2fb1800",
   "metadata": {},
   "outputs": [],
   "source": [
    "// @lc-docs-hide-cell\n",
    "import { OpenAIEmbeddings } from \"@langchain/openai\";\n",
    "\n",
    "const embeddings = new OpenAIEmbeddings({model: \"text-embedding-3-large\"});"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5b6f17a6-4466-4275-bc52-be21b93348bf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated vectors of length 3072\n",
      "\n",
      "[\n",
      "  \u001b[33m0.014310152\u001b[39m,\n",
      "  \u001b[33m-0.01681044\u001b[39m,\n",
      "  \u001b[33m-0.0011537228\u001b[39m,\n",
      "  \u001b[33m0.010546423\u001b[39m,\n",
      "  \u001b[33m0.022808468\u001b[39m,\n",
      "  \u001b[33m-0.028327717\u001b[39m,\n",
      "  \u001b[33m-0.00058849837\u001b[39m,\n",
      "  \u001b[33m0.0419197\u001b[39m,\n",
      "  \u001b[33m-0.0012900416\u001b[39m,\n",
      "  \u001b[33m0.0661778\u001b[39m\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "const vector1 = await embeddings.embedQuery(allSplits[0].pageContent)\n",
    "const vector2 = await embeddings.embedQuery(allSplits[1].pageContent)\n",
    "\n",
    "\n",
    "console.assert(vector1.length === vector2.length);\n",
    "console.log(`Generated vectors of length ${vector1.length}\\n`);\n",
    "console.log(vector1.slice(0, 10));"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cac19bd-27d1-40f1-9c27-7a586b685b4e",
   "metadata": {},
   "source": [
    "Armed with a model for generating text embeddings, we can next store them in a special data structure that supports efficient similarity search.\n",
    "\n",
    "## Vector stores\n",
    "\n",
    "LangChain [VectorStore](https://api.js.langchain.com/classes/_langchain_core.vectorstores.VectorStore.html) objects contain methods for adding text and `Document` objects to the store, and querying them using various similarity metrics. They are often initialized with [embedding](/docs/how_to/embed_text) models, which determine how text data is translated to numeric vectors.\n",
    "\n",
    "LangChain includes a suite of [integrations](/docs/integrations/vectorstores) with different vector store technologies. Some vector stores are hosted by a provider (e.g., various cloud providers) and require specific credentials to use; some (such as [Postgres](/docs/integrations/vectorstores/pgvector)) run in separate infrastructure that can be run locally or via a third-party; others can run in-memory for lightweight workloads.\n",
    "\n",
    "```{=mdx}\n",
    "import VectorStoreTabs from \"@theme/VectorStoreTabs\";\n",
    "\n",
    "<VectorStoreTabs/>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5b7d2138-5881-4ffe-99f5-fd547bd32b3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "// @lc-docs-hide-cell\n",
    "import { MemoryVectorStore } from \"langchain/vectorstores/memory\";\n",
    "\n",
    "const vectorStore = new MemoryVectorStore(embeddings);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3b3035f-1371-4965-ab7a-04eae25e47f3",
   "metadata": {},
   "source": [
    "Having instantiated our vector store, we can now index the documents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2ea92e04-331c-4f83-aa2a-508322bdfbfc",
   "metadata": {},
   "outputs": [],
   "source": [
    "await vectorStore.addDocuments(allSplits)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff0f0b43-e5b8-4c79-b782-a02f17345487",
   "metadata": {},
   "source": [
    "Note that most vector store implementations will allow you to connect to an existing vector store--  e.g., by providing a client, index name, or other information. See the documentation for a specific [integration](/docs/integrations/vectorstores) for more detail.\n",
    "\n",
    "Once we've instantiated a `VectorStore` that contains documents, we can query it. [VectorStore](https://api.js.langchain.com/classes/_langchain_core.vectorstores.VectorStore.html) includes methods for querying:\n",
    "- Synchronously and asynchronously;\n",
    "- By string query and by vector;\n",
    "- With and without returning similarity scores;\n",
    "- By similarity and [maximum marginal relevance](https://api.js.langchain.com/classes/_langchain_core.vectorstores.VectorStore.html#maxMarginalRelevanceSearch) (to balance similarity with query to diversity in retrieved results).\n",
    "\n",
    "The methods will generally include a list of [Document](https://api.js.langchain.com/classes/_langchain_core.documents.Document.html) objects in their outputs.\n",
    "\n",
    "### Usage\n",
    "\n",
    "Embeddings typically represent text as a \"dense\" vector such that texts with similar meanings are gemoetrically close. This lets us retrieve relevant information just by passing in a question, without knowledge of any specific key-terms used in the document.\n",
    "\n",
    "Return documents based on similarity to a string query:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7b716152-0076-46b1-9486-bdbed7e90730",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Document {\n",
      "  pageContent: \u001b[32m'Table of Contents\\n'\u001b[39m +\n",
      "    \u001b[32m'PART I\\n'\u001b[39m +\n",
      "    \u001b[32m'ITEM 1. BUSINESS\\n'\u001b[39m +\n",
      "    \u001b[32m'GENERAL\\n'\u001b[39m +\n",
      "    \u001b[32m'NIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this \"Annual Report\"), the terms \"we,\" \"us,\" \"our,\"\\n'\u001b[39m +\n",
      "    \u001b[32m'\"NIKE\" and the \"Company\" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise.\\n'\u001b[39m +\n",
      "    \u001b[32m'Our principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is\\n'\u001b[39m +\n",
      "    \u001b[32m'the largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores\\n'\u001b[39m +\n",
      "    \u001b[32m'and sales through our digital platforms (also referred to as \"NIKE Brand Digital\"), to retail accounts and to a mix of independent distributors, licensees and sales'\u001b[39m,\n",
      "  metadata: {\n",
      "    source: \u001b[32m'../../data/nke-10k-2023.pdf'\u001b[39m,\n",
      "    pdf: {\n",
      "      version: \u001b[32m'1.10.100'\u001b[39m,\n",
      "      info: \u001b[36m[Object]\u001b[39m,\n",
      "      metadata: \u001b[1mnull\u001b[22m,\n",
      "      totalPages: \u001b[33m107\u001b[39m\n",
      "    },\n",
      "    loc: { pageNumber: \u001b[33m4\u001b[39m, lines: \u001b[36m[Object]\u001b[39m }\n",
      "  },\n",
      "  id: \u001b[90mundefined\u001b[39m\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "const results1 = await vectorStore.similaritySearch(\"When was Nike incorporated?\")\n",
    "\n",
    "results1[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4172698-9ad7-4422-99b2-bdc268e99c75",
   "metadata": {},
   "source": [
    "Return scores:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a8c3af60-7328-45eb-bc27-69e640ebff6d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\n",
      "  Document {\n",
      "    pageContent: \u001b[32m'Table of Contents\\n'\u001b[39m +\n",
      "      \u001b[32m'FISCAL 2023 NIKE BRAND REVENUE HIGHLIGHTS\\n'\u001b[39m +\n",
      "      \u001b[32m'The following tables present NIKE Brand revenues disaggregated by reportable operating segment, distribution channel and major product line:\\n'\u001b[39m +\n",
      "      \u001b[32m'FISCAL 2023 COMPARED TO FISCAL 2022\\n'\u001b[39m +\n",
      "      \u001b[32m'•NIKE, Inc. Revenues were $51.2 billion in fiscal 2023, which increased 10% and 16% compared to fiscal 2022 on a reported and currency-neutral basis, respectively.\\n'\u001b[39m +\n",
      "      \u001b[32m'The increase was due to higher revenues in North America, Europe, Middle East & Africa (\"EMEA\"), APLA and Greater China, which contributed approximately 7, 6,\\n'\u001b[39m +\n",
      "      \u001b[32m'2 and 1 percentage points to NIKE, Inc. Revenues, respectively.\\n'\u001b[39m +\n",
      "      \u001b[32m'•NIKE Brand revenues, which represented over 90% of NIKE, Inc. Revenues, increased 10% and 16% on a reported and currency-neutral basis, respectively. This\\n'\u001b[39m +\n",
      "      \u001b[32m\"increase was primarily due to higher revenues in Men's, the Jordan Brand, Women's and Kids' which grew 17%, 35%,11% and 10%, respectively, on a wholesale\\n\"\u001b[39m +\n",
      "      \u001b[32m'equivalent basis.'\u001b[39m,\n",
      "    metadata: {\n",
      "      source: \u001b[32m'../../data/nke-10k-2023.pdf'\u001b[39m,\n",
      "      pdf: \u001b[36m[Object]\u001b[39m,\n",
      "      loc: \u001b[36m[Object]\u001b[39m\n",
      "    },\n",
      "    id: \u001b[90mundefined\u001b[39m\n",
      "  },\n",
      "  \u001b[33m0.6992287611800424\u001b[39m\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "const results2 = await vectorStore.similaritySearchWithScore(\n",
    "    \"What was Nike's revenue in 2023?\"\n",
    ")\n",
    "\n",
    "results2[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4991642-7275-40a9-b11a-e3beccbf2614",
   "metadata": {},
   "source": [
    "Return documents based on similarity to an embedded query:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "fd2db600-5919-41f2-9f78-a9bae537d910",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\n",
      "  Document {\n",
      "    pageContent: \u001b[32m'Table of Contents\\n'\u001b[39m +\n",
      "      \u001b[32m'GROSS MARGIN\\n'\u001b[39m +\n",
      "      \u001b[32m'FISCAL 2023 COMPARED TO FISCAL 2022\\n'\u001b[39m +\n",
      "      \u001b[32m'For fiscal 2023, our consolidated gross profit increased 4% to $22,292 million compared to $21,479 million for fiscal 2022. Gross margin decreased 250 basis points to\\n'\u001b[39m +\n",
      "      \u001b[32m'43.5% for fiscal 2023 compared to 46.0% for fiscal 2022 due to the following:\\n'\u001b[39m +\n",
      "      \u001b[32m'*Wholesale equivalent\\n'\u001b[39m +\n",
      "      \u001b[32m'The decrease in gross margin for fiscal 2023 was primarily due to:\\n'\u001b[39m +\n",
      "      \u001b[32m'•Higher NIKE Brand product costs, on a wholesale equivalent basis, primarily due to higher input costs and elevated inbound freight and logistics costs as well as\\n'\u001b[39m +\n",
      "      \u001b[32m'product mix;\\n'\u001b[39m +\n",
      "      \u001b[32m'•Lower margin in our NIKE Direct business, driven by higher promotional activity to liquidate inventory in the current period compared to lower promotional activity in\\n'\u001b[39m +\n",
      "      \u001b[32m'the prior period resulting from lower available inventory supply;\\n'\u001b[39m +\n",
      "      \u001b[32m'•Unfavorable changes in net foreign currency exchange rates, including hedges; and\\n'\u001b[39m +\n",
      "      \u001b[32m'•Lower off-price margin, on a wholesale equivalent basis.\\n'\u001b[39m +\n",
      "      \u001b[32m'This was partially offset by:'\u001b[39m,\n",
      "    metadata: {\n",
      "      source: \u001b[32m'../../data/nke-10k-2023.pdf'\u001b[39m,\n",
      "      pdf: \u001b[36m[Object]\u001b[39m,\n",
      "      loc: \u001b[36m[Object]\u001b[39m\n",
      "    },\n",
      "    id: \u001b[90mundefined\u001b[39m\n",
      "  },\n",
      "  \u001b[33m0.7368815472158006\u001b[39m\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "const embedding = await embeddings.embedQuery(\n",
    "    \"How were Nike's margins impacted in 2023?\"\n",
    ")\n",
    "\n",
    "const results3 = await vectorStore.similaritySearchVectorWithScore(\n",
    "    embedding, 1\n",
    ")\n",
    "\n",
    "results3[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "168dbbec-ea97-4cc9-bb1a-75519c2d08af",
   "metadata": {},
   "source": [
    "Learn more:\n",
    "\n",
    "- [API reference](https://api.js.langchain.com/classes/_langchain_core.vectorstores.VectorStore.html)\n",
    "- [How-to guide](/docs/how_to/vectorstores)\n",
    "- [Integration-specific docs](/docs/integrations/vectorstores)\n",
    "\n",
    "## Retrievers\n",
    "\n",
    "LangChain `VectorStore` objects do not subclass [Runnable](https://api.js.langchain.com/classes/_langchain_core.runnables.Runnable.html). LangChain [Retrievers](https://api.js.langchain.com/classes/_langchain_core.retrievers.BaseRetriever.html) are Runnables, so they implement a standard set of methods (e.g., synchronous and asynchronous `invoke` and `batch` operations). Although we can construct retrievers from vector stores, retrievers can interface with non-vector store sources of data, as well (such as external APIs).\n",
    "\n",
    "Vectorstores implement an [as retriever](https://api.js.langchain.com/classes/_langchain_core.vectorstores.VectorStore.html#asRetriever) method that will generate a Retriever, specifically a [VectorStoreRetriever](https://api.js.langchain.com/classes/_langchain_core.vectorstores.VectorStoreRetriever.html). These retrievers include specific `search_type` and `search_kwargs` attributes that identify what methods of the underlying vector store to call, and how to parameterize them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "90d1f87b-30fe-4e1e-af8b-9e1f04e75f66",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\n",
      "  [\n",
      "    Document {\n",
      "      pageContent: \u001b[32m'Table of Contents\\n'\u001b[39m +\n",
      "        \u001b[32m'PART I\\n'\u001b[39m +\n",
      "        \u001b[32m'ITEM 1. BUSINESS\\n'\u001b[39m +\n",
      "        \u001b[32m'GENERAL\\n'\u001b[39m +\n",
      "        \u001b[32m'NIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this \"Annual Report\"), the terms \"we,\" \"us,\" \"our,\"\\n'\u001b[39m +\n",
      "        \u001b[32m'\"NIKE\" and the \"Company\" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise.\\n'\u001b[39m +\n",
      "        \u001b[32m'Our principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is\\n'\u001b[39m +\n",
      "        \u001b[32m'the largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores\\n'\u001b[39m +\n",
      "        \u001b[32m'and sales through our digital platforms (also referred to as \"NIKE Brand Digital\"), to retail accounts and to a mix of independent distributors, licensees and sales'\u001b[39m,\n",
      "      metadata: \u001b[36m[Object]\u001b[39m,\n",
      "      id: \u001b[90mundefined\u001b[39m\n",
      "    }\n",
      "  ],\n",
      "  [\n",
      "    Document {\n",
      "      pageContent: \u001b[32m'Table of Contents\\n'\u001b[39m +\n",
      "        \u001b[32m'FISCAL 2023 NIKE BRAND REVENUE HIGHLIGHTS\\n'\u001b[39m +\n",
      "        \u001b[32m'The following tables present NIKE Brand revenues disaggregated by reportable operating segment, distribution channel and major product line:\\n'\u001b[39m +\n",
      "        \u001b[32m'FISCAL 2023 COMPARED TO FISCAL 2022\\n'\u001b[39m +\n",
      "        \u001b[32m'•NIKE, Inc. Revenues were $51.2 billion in fiscal 2023, which increased 10% and 16% compared to fiscal 2022 on a reported and currency-neutral basis, respectively.\\n'\u001b[39m +\n",
      "        \u001b[32m'The increase was due to higher revenues in North America, Europe, Middle East & Africa (\"EMEA\"), APLA and Greater China, which contributed approximately 7, 6,\\n'\u001b[39m +\n",
      "        \u001b[32m'2 and 1 percentage points to NIKE, Inc. Revenues, respectively.\\n'\u001b[39m +\n",
      "        \u001b[32m'•NIKE Brand revenues, which represented over 90% of NIKE, Inc. Revenues, increased 10% and 16% on a reported and currency-neutral basis, respectively. This\\n'\u001b[39m +\n",
      "        \u001b[32m\"increase was primarily due to higher revenues in Men's, the Jordan Brand, Women's and Kids' which grew 17%, 35%,11% and 10%, respectively, on a wholesale\\n\"\u001b[39m +\n",
      "        \u001b[32m'equivalent basis.'\u001b[39m,\n",
      "      metadata: \u001b[36m[Object]\u001b[39m,\n",
      "      id: \u001b[90mundefined\u001b[39m\n",
      "    }\n",
      "  ]\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "const retriever = vectorStore.asRetriever({\n",
    "  searchType: \"mmr\",\n",
    "  searchKwargs: {\n",
    "    fetchK: 1,\n",
    "  },\n",
    "});\n",
    "\n",
    "\n",
    "await retriever.batch(\n",
    "    [\n",
    "        \"When was Nike incorporated?\",\n",
    "        \"What was Nike's revenue in 2023?\",\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b79ded3-39ed-4aeb-8b70-cd36795ae239",
   "metadata": {},
   "source": [
    "`VectorStoreRetriever` supports search types of `\"similarity\"` (default) and `\"mmr\"` (maximum marginal relevance, described above).\n",
    "\n",
    "Retrievers can easily be incorporated into more complex applications, such as [retrieval-augmented generation (RAG)](/docs/concepts/rag) applications that combine a given question with retrieved context into a prompt for a LLM. To learn more about building such an application, check out the [RAG tutorial](/docs/tutorials/rag) tutorial."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d9be7cb-2081-48a4-b6e4-d5e2d562ffd4",
   "metadata": {},
   "source": [
    "### Learn more:\n",
    "\n",
    "Retrieval strategies can be rich and complex. For example:\n",
    "\n",
    "- We can [infer hard rules and filters](/docs/how_to/self_query/) from a query (e.g., \"using documents published after 2020\");\n",
    "- We can [return documents that are linked](/docs/how_to/parent_document_retriever/) to the retrieved context in some way (e.g., via some document taxonomy);\n",
    "- We can generate [multiple embeddings](/docs/how_to/multi_vector) for each unit of context;\n",
    "- We can [ensemble results](/docs/how_to/ensemble_retriever) from multiple retrievers;\n",
    "- We can assign weights to documents, e.g., to weigh [recent documents](/docs/how_to/time_weighted_vectorstore/) higher.\n",
    "\n",
    "The [retrievers](/docs/how_to#retrievers) section of the how-to guides covers these and other built-in retrieval strategies.\n",
    "\n",
    "It is also straightforward to extend the [BaseRetriever](https://api.js.langchain.com/classes/_langchain_core.retrievers.BaseRetriever.html) class in order to implement custom retrievers. See our how-to guide [here](/docs/how_to/custom_retriever).\n",
    "\n",
    "\n",
    "## Next steps\n",
    "\n",
    "You've now seen how to build a semantic search engine over a PDF document.\n",
    "\n",
    "For more on document loaders:\n",
    "\n",
    "- [Conceptual guide](/docs/concepts/document_loaders)\n",
    "- [How-to guides](/docs/how_to/#document-loaders)\n",
    "- [Available integrations](/docs/integrations/document_loaders/)\n",
    "\n",
    "For more on embeddings:\n",
    "\n",
    "- [Conceptual guide](/docs/concepts/embedding_models/)\n",
    "- [How-to guides](/docs/how_to/#embedding-models)\n",
    "- [Available integrations](/docs/integrations/text_embedding/)\n",
    "\n",
    "For more on vector stores:\n",
    "\n",
    "- [Conceptual guide](/docs/concepts/vectorstores/)\n",
    "- [How-to guides](/docs/how_to/#vector-stores)\n",
    "- [Available integrations](/docs/integrations/vectorstores/)\n",
    "\n",
    "For more on RAG, see:\n",
    "\n",
    "- [Build a Retrieval Augmented Generation (RAG) App](/docs/tutorials/rag/)\n",
    "- [Related how-to guides](/docs/how_to/#qa-with-rag)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "TypeScript",
   "language": "typescript",
   "name": "tslab"
  },
  "language_info": {
   "codemirror_mode": {
    "mode": "typescript",
    "name": "javascript",
    "typescript": true
   },
   "file_extension": ".ts",
   "mimetype": "text/typescript",
   "name": "typescript",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
